import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const User2UserSchema = new mongoose.Schema({
    userId: String,
    userObj: Object,
    user2Id: String,
    user2Obj: Object,
    type: String,
    createTime: Number
});

User2UserSchema.methods.saveUser2User = function (user2User, cb) {
    user2User.createTime = moment().unix();
    this.model('user2User').insertMany([user2User], cb);
};

User2UserSchema.methods.getUser2Users = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const user2UserModel = this.model('user2User');
    user2UserModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        user2UserModel.find(leftQuery, { passwd: 0 }).skip((current - 1) * pageSize).limit(pageSize).exec((err, user2Users) => cb(err, user2Users, count, hasMore));
    });
};

User2UserSchema.methods.getAllUser2Users = function (query, cb) {
    this.model('user2User').find(query, cb);
};

User2UserSchema.methods.getUser2User = function (query, cb) {
    this.model('user2User').findOne(query, cb);
};

User2UserSchema.methods.updateUser2User = function (user2User, cb) {
    const _id = user2User._id;
    delete user2User._id;
    this.model('user2User').findOneAndUpdate({ _id }, { $set: user2User }, cb);
};

User2UserSchema.methods.removeUser2Users = function (user2UserIds, cb) {
    this.model('user2User').remove({ _id: { $in: user2UserIds } }, cb);
};

export default db.model('user2User', User2UserSchema);